package com.shaoshaohuo.app.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TabHost;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.PublishedGoodsListAdapter;
import com.shaoshaohuo.app.adapter.PurchaseRecordListAdapter;
import com.shaoshaohuo.app.adapter.SupplyRecordListAdapter;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.constant.ListViewAction;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.PublishedGoodsItem;
import com.shaoshaohuo.app.entity.PublishedGoodsListEntity;
import com.shaoshaohuo.app.entity.PurchaseRecord;
import com.shaoshaohuo.app.entity.PurchaseRecordEntity;
import com.shaoshaohuo.app.entity.SupplyRecord;
import com.shaoshaohuo.app.entity.SupplyRecordEntity;
import com.shaoshaohuo.app.framework.IViewFramework;
import com.shaoshaohuo.app.net.HttpRequest;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.ec.PurchaseDetailActivity;
import com.shaoshaohuo.app.ui.ec.PurchaseRecordDetailActivity;
import com.shaoshaohuo.app.ui.ec.SupplyDetailActivity;
import com.shaoshaohuo.app.ui.shipper.CarOwnerInfoActivity;
import com.shaoshaohuo.app.utils.StringUtil;
import com.shaoshaohuo.app.utils.ViewHelper;
import com.shaoshaohuo.app.utils.ViewUtil;
import com.shaoshaohuo.app.view.TopbarView;
import com.shaoshaohuo.app.view.XListView;

import java.util.ArrayList;
import java.util.List;

/**
 * 发布管理
 * Created by YinSF on 16/1/14.
 */
public class PublishManagerActivity extends BaseActivity implements IViewFramework, View.OnClickListener,
        TabHost.OnTabChangeListener, XListView.IXListViewListener {
    private View view;
    private TopbarView topBar;
    private String mArgument;
    public static final String ARGUMENT = "argument";
//    public static final String ARGUMENT_VALUE_WITH_BACK = "ARGUMENT_VALUE_WITH_BACK";
    private static final String TAB_ONE = "TAB_ONE";
    private static final String TAB_TWO = "TAB_TWO";
//    private static final String TAB_THREE = "TAB_THREE";
    private static final String TAB_FOUR = "TAB_FOUR";
    private TabHost tabHost;
    private XListView mBuyListView;
    private XListView mSellListView;
//    private XListView mCarPriceListView;
    private XListView mGoodsListView;

    private int size = 10;
    private String actionBuy = ListViewAction.NEW;
    private String actionSell = ListViewAction.NEW;
//    private String actionCar = ListViewAction.NEW;
    private String actionGoods = ListViewAction.NEW;

    private String cursorBuy = "0";
    private String cursorSell = "0";
//    private String cursorCarPrice = "0";
    private String cursorGoods = "0";

    private PurchaseRecordListAdapter<PurchaseRecord> mAdapterBuy;
    private SupplyRecordListAdapter<SupplyRecord> mAdapterSell;
    private PublishedGoodsListAdapter<PublishedGoodsItem> mAdapterGoods;

    private List<PurchaseRecord> mDataListBuy = new ArrayList<PurchaseRecord>();
    private List<SupplyRecord> mDataListSell = new ArrayList<SupplyRecord>();
    private List<PublishedGoodsItem> mDataListGoods = new ArrayList<PublishedGoodsItem>();

    private static String CURRENT_TAB = TAB_ONE;

    //选择货源模式
    public static String EXTRA_SELECT_GOODS = "EXTRA_SELECT_GOODS";
    private boolean isSelectGoodsStatus = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_manager);
        if (!StringUtil.isEmpty(getIntent().getStringExtra(EXTRA_SELECT_GOODS))) {
            isSelectGoodsStatus = true;
            CURRENT_TAB = TAB_FOUR;
        }
        init();
    }

    @Override
    public void init() {
        initView();
        initListener();
    }

    @Override
    public void initView() {
        topBar = (TopbarView) findViewById(R.id.topbar);
        topBar.setCenterText("我的发布");
        topBar.setLeftClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        topBar.setRightImage(R.drawable.icon_add_ad);
        topBar.setRightImage(ViewUtil.dip2px(this, 45), ViewUtil.dip2px(this, 45));
        topBar.setRightClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(PublishManagerActivity.this, ReleaseActivity.class));
            }
        });
        tabHost = (TabHost) findViewById(android.R.id.tabhost);
        tabHost.setup();
        TabHost.TabSpec tab1 = tabHost.newTabSpec(TAB_ONE);
        tab1.setIndicator("采购");
        tab1.setContent(R.id.linearLayout_buy);
        tabHost.addTab(tab1);
        TabHost.TabSpec tab2 = tabHost.newTabSpec(TAB_TWO);
        tab2.setIndicator("供应");
        tab2.setContent(R.id.linearLayout_sell);
        tabHost.addTab(tab2);
//        TabHost.TabSpec tab3 = tabHost.newTabSpec(TAB_THREE);
//        tab3.setIndicator("车源");
//        tab3.setContent(R.id.linearLayout_car);
//        tabHost.addTab(tab3);
        TabHost.TabSpec tab4 = tabHost.newTabSpec(TAB_FOUR);
        tab4.setIndicator("物流");
        tab4.setContent(R.id.linearLayout_goods);
        tabHost.addTab(tab4);
        if (isSelectGoodsStatus) {
            tabHost.setEnabled(false);
            tabHost.setClickable(false);
        }

        tabHost.setCurrentTabByTag(CURRENT_TAB);

        ViewHelper.setTabHostStyle(tabHost.getTabWidget(), this, tabHost.getCurrentTab());
        mBuyListView = (XListView) findViewById(R.id.listview_buy);
        mSellListView = (XListView) findViewById(R.id.listview_sell);
//        mCarPriceListView = (XListView) findViewById(R.id.listview_car);
        mGoodsListView = (XListView) findViewById(R.id.listview_goods);
    }

    @Override
    public void initData() {
        String currentTabTag = tabHost.getCurrentTabTag();
        if (TAB_ONE.equals(currentTabTag)) {
            requestDataBuy(true);
        } else if (TAB_TWO.equals(currentTabTag)) {
            requestDataSell(true);
//        } else if (TAB_THREE.equals(currentTabTag)) {

        } else if (TAB_FOUR.equals(currentTabTag)) {
            requestDataGoods(true);
        }
    }

    private void requestDataGoods(boolean isLoading) {
        if(isLoading){
            startLoadingDialog();
        }
        RequestService.getInstance().publishedGoodsList(this, cursorGoods, size + "", PublishedGoodsListEntity.class, new HttpRequest.RequestListener() {

            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if (resultData.isOk()) {
                    PublishedGoodsListEntity entity = (PublishedGoodsListEntity) resultData;
                    if (entity.getData() != null) {
                        List<PublishedGoodsItem> list = entity.getData().getList();
                        mDataListGoods.addAll(list);
                    }
                    if (entity.getData() != null || (mDataListGoods.size() < size) || (actionGoods.equals(ListViewAction.HISTORY) && entity.getData().getList().size() < size)) {
                        mGoodsListView.endLoadingMore("没有更多了");
                    }
                    setAdapterGoods(mDataListGoods);

                } else {
                    showToast(resultData.getMsg());
                }
                onLoad();
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
                showToast(msg);
                onLoad();
            }
        });
    }

    /**
     * 货源列表
     * @param mDataListGoods
     */
    private void setAdapterGoods(List<PublishedGoodsItem> mDataListGoods) {
        if(mAdapterGoods == null){
            mAdapterGoods = new PublishedGoodsListAdapter<PublishedGoodsItem>(this, mDataListGoods, false);
            mGoodsListView.setAdapter(mAdapterGoods);
        }else{
            mAdapterGoods.setData(mDataListGoods);
        }
    }


    /**
     * 获取发布的采购记录
     * @param isLoading
     */
    private void requestDataBuy(boolean isLoading) {
        if(isLoading){
            startLoadingDialog();
        }
        RequestService.getInstance().purchasePublishedMyList(this, cursorBuy, size+"", actionBuy, PurchaseRecordEntity.class, new HttpRequest.RequestListener() {

            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if(resultData.isOk()){
                    PurchaseRecordEntity entity = (PurchaseRecordEntity) resultData;
                    List<PurchaseRecord> list = entity.getData().getList();
                    mDataListBuy.addAll(list);

                    if ((mDataListBuy.size() < size) || (actionBuy.equals(ListViewAction.HISTORY) && list.size() < size)) {
                        mBuyListView.endLoadingMore("没有更多了");
                    }
                    setAdapterBuy(mDataListBuy);

                }else{
                    showToast(resultData.getMsg());
                }
                onLoad();
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
                showToast(msg);
                onLoad();
            }
        });
    }

    /**
     * 设置采购数据适配器
     * @param mDataList2
     */
    protected void setAdapterBuy(List<PurchaseRecord> mDataList2) {
        if(mAdapterBuy == null){
            mAdapterBuy = new PurchaseRecordListAdapter<PurchaseRecord>(this, mDataList2, false);
            mBuyListView.setAdapter(mAdapterBuy);
        }else{
            mAdapterBuy.setData(mDataList2);
        }
    }

    /**
     * 请求供应记录
     * @param isLoading
     */
    private void requestDataSell(boolean isLoading) {
        if (isLoading) {
            startLoadingDialog();
        }
        RequestService.getInstance().supplyPublishMyList(this, cursorSell, size + "", actionSell, SupplyRecordEntity.class,
                new HttpRequest.RequestListener() {

                    @Override
                    public void onSuccess(int requestCode, BaseEntity resultData) {
                        dismissLoadingDialog();
                        if (resultData.isOk()) {
                            SupplyRecordEntity entity = (SupplyRecordEntity) resultData;
                            List<SupplyRecord> list = entity.getData().getList();
                            mDataListSell.addAll(list);

                            if ((mDataListSell.size() < size) || (actionSell.equals(ListViewAction.HISTORY) && list.size() < size)) {
                                mSellListView.endLoadingMore("没有更多了");
                            }
                            setAdapterSell(mDataListSell);

                        } else {
                            showToast(resultData.getMsg());
                        }
                        onLoad();
                    }

                    @Override
                    public void onFailed(int requestCode, Exception error, String msg) {
                        dismissLoadingDialog();
                        showToast(msg);
                        onLoad();
                    }
                });
    }

    protected void setAdapterSell(List<SupplyRecord> mDataList2) {
        if (mAdapterSell == null) {
            mAdapterSell = new SupplyRecordListAdapter<SupplyRecord>(this, mDataList2, false);
            mSellListView.setAdapter(mAdapterSell);
        } else {
            mAdapterSell.setData(mDataList2);
        }
    }

    @Override
    public void initListener() {
        tabHost.setOnTabChangedListener(this);
        setListView();
    }

    private void setListView() {
        //采购
        mBuyListView.setPullLoadEnable(true);
        mBuyListView.setPullRefreshEnable(true);
        mBuyListView.setXListViewListener(this);

        mBuyListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                PurchaseRecord order = (PurchaseRecord) parent.getItemAtPosition(position);
                Intent intent = new Intent(PublishManagerActivity.this,PurchaseDetailActivity.class);
                intent.putExtra(ExtraName.id, order.getId());
                startActivity(intent);
            }
        });

        //供应
        mSellListView.setPullLoadEnable(true);
        mSellListView.setPullRefreshEnable(true);
        mSellListView.setXListViewListener(this);

        mSellListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                SupplyRecord order = (SupplyRecord) parent.getItemAtPosition(position);
                Intent intent = new Intent(PublishManagerActivity.this, SupplyDetailActivity.class);
                intent.putExtra(ExtraName.id, order.getId());
                intent.putExtra("myinfo", true);
                startActivity(intent);
            }
        });

        //货源
        mGoodsListView.setPullLoadEnable(true);
        mGoodsListView.setPullRefreshEnable(true);
        mGoodsListView.setXListViewListener(this);

        mGoodsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                PublishedGoodsItem cargo = (PublishedGoodsItem) parent.getItemAtPosition(position);
                if (isSelectGoodsStatus) {
                    Intent data = new Intent();
                    data.putExtra(CarOwnerInfoActivity.EXTRA_GOODS_ID, cargo.getOrderid());
                    setResult(RESULT_OK, data);
                    finish();
                } else {
                    Intent intent = new Intent(PublishManagerActivity.this, GrabOrderActivity.class);
                    intent.putExtra(ExtraName.orderid, cargo.getOrderid());
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onRefresh() {
        String currentTabTag = tabHost.getCurrentTabTag();
        if (TAB_ONE.equals(currentTabTag)) {
            cursorBuy = "0";
            mDataListBuy.clear();
            actionBuy = ListViewAction.NEW;
            mBuyListView.setPullLoadEnable(true);
            requestDataBuy(false);
        } else if (TAB_TWO.equals(currentTabTag)) {
            cursorSell = "0";
            mDataListSell.clear();
            actionSell = ListViewAction.NEW;
            mSellListView.setPullLoadEnable(true);
            requestDataSell(false);
//        } else if (TAB_THREE.equals(currentTabTag)) {

        } else if (TAB_FOUR.equals(currentTabTag)) {
            cursorGoods = "0";
            mDataListGoods.clear();
            actionGoods = ListViewAction.NEW;
            mGoodsListView.setPullLoadEnable(true);
            requestDataGoods(false);
        }

    }

    @Override
    public void onLoadMore() {
        String currentTabTag = tabHost.getCurrentTabTag();
        if (TAB_ONE.equals(currentTabTag)) {
            if(mDataListBuy.size()>0){
                cursorBuy = mDataListBuy.get(mDataListBuy.size()-1).getCursor();
            }else {
                cursorBuy = "0";
            }
            actionBuy = ListViewAction.HISTORY;
            requestDataBuy(false);
        } else if (TAB_TWO.equals(currentTabTag)) {
            if (mDataListSell.size() > 0) {
                cursorSell = mDataListSell.get(mDataListSell.size() - 1).getCursor();
            } else {
                cursorSell = "0";
            }
            actionSell = ListViewAction.HISTORY;
            requestDataSell(false);
//        } else if (TAB_THREE.equals(currentTabTag)) {

        } else if (TAB_FOUR.equals(currentTabTag)) {
            if (mDataListGoods.size() > 0) {
                cursorGoods = mDataListGoods.get(mDataListGoods.size() - 1).getCursor();
            } else {
                cursorGoods = "0";
            }
            actionGoods = ListViewAction.HISTORY;
            requestDataGoods(false);
        }
    }

    @Override
    public void onTabChanged(String tabId) {
        ViewHelper.setTabHostStyle(tabHost.getTabWidget(), this, tabHost.getCurrentTab());
        CURRENT_TAB = tabId;
        onRefresh();
    }

    private void onLoad() {
        String currentTabTag = tabHost.getCurrentTabTag();
        if (TAB_ONE.equals(currentTabTag)) {
            mBuyListView.stopRefresh();
            mBuyListView.stopLoadMore();
        } else if (TAB_TWO.equals(currentTabTag)) {
            mSellListView.stopRefresh();
            mSellListView.stopLoadMore();
//        } else if (TAB_THREE.equals(currentTabTag)) {

        } else if (TAB_FOUR.equals(currentTabTag)) {
            mGoodsListView.stopRefresh();
            mGoodsListView.stopLoadMore();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        onRefresh();
    }
}
